package com.sunday.common.netty.e8_Handlerorder.server.inbound;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class InBoundWritingHandler extends ChannelInboundHandlerAdapter {
    static AtomicInteger count = new AtomicInteger(0);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("[In][last][Into] InBoundWritingHandler.channelRead");
        String data = ((ByteBuf) msg).toString(CharsetUtil.UTF_8);
        log.info("[In][last][receive] InBoundWritingHandler.channelRead receive: " + data);
        ctx.writeAndFlush(Unpooled.copiedBuffer("TCP Server had got msg, index = " + count.incrementAndGet(),
                CharsetUtil.UTF_8));
        // If do not call fireChannelRead, the next ChannelHandler will not exec.
        ctx.fireChannelRead(msg);
        log.info("[In][last][Exit] InBoundWritingHandler channelRead");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("[In][last][readComplete] InBoundWritingHandler readComplete.");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("[In][last][exceptionCaught] InBoundWritingHandler exceptionCaught.");
    }

}